package com.atguigu.sort;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

/**
 * @Author : SunFeng
 * @Description:
 * @Date : 2021/7/6  10:31
 */
public class MergeSort {
    public static void main(String[] args) {
        //int[] array = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] array = new int[8000];
        for (int i = 0; i < 8000; i++) {
            array[i] = (int) (Math.random() * 8000);
        }
        System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 创建临时数组进行数据保存,保证不重复创建相应数组来存放数据
        int[] temp = new int[array.length];
        mergeSort(array, 0, array.length - 1, temp);

        System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        System.out.println(Arrays.toString(array));
    }


    public static void mergeSort(int[] array, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;

            mergeSort(array, left, mid, temp);
            mergeSort(array, mid + 1, right, temp);

            merge(array, left, mid, right, temp);

        }

    }


    /**
     * 归并
     *
     * @param array
     * @param left
     * @param mid
     * @param right
     * @param temp
     */
    public static void merge(int[] array, int left, int mid, int right, int[] temp) {
        // 初始化左边数组初始索引
        int i = left;
        //初始化右边数组初始索引
        int j = mid + 1;
        //初始化临时数组索引
        int t = 0;

        while (i < mid && j < right) {
            if (array[i] < array[j]) {
                temp[t++] = array[i++];
            } else {
                temp[t++] = array[j++];
            }
        }
        // 如果左边还有剩余
        while (i <= mid) {
            temp[t++] = array[i++];
        }

        // 如果右边有剩余
        while (j <= right) {
            temp[t++] = array[j++];
        }


        // 将tmp数组赋值给arr------tmp是有序数组  从 原始数组的最左边开始赋值
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            array[tempLeft++] = temp[t++];
        }
    }
}
